<?php

/**
 * 订单_模型
 * @property Order_queue_mdl $orderQueue
 * @property User_mdl $users
 */
class Order_mdl extends MY_Model {
	public function __construct() {
		parent::__construct ();
		$this->load->database();
		$this->_table = parent::T_ORDER;
	}


	/**
	 * 检查用户是否有未完成订单
	 * @param int $userID
	 * @return boolean
	 */
	public function checkUserHasUnfinishOrder($userID){
		return ( bool ) $this->db->select ( 'id' )
								->from ( $this->_table )
								->where ( 'userID', $userID )
								->where ( 'isFinish', 0 )
								->limit ( 1 )
								->get ()
								->num_rows ();
	}

	/**
	 * 获取一个用户的未完成订单
	 * @param int $uid
	 */
	public function getUserUnfinishOrders($uid){
		$where = array(
				'userID'=>$uid,
				'isFinish'=>0,
		);
		return $this->getList('*',$where);
	}

	/**
	 * 结算订单
	 * @param array|int $order	订单详情数组或订单ID
	 * @param int $endTime	结算时间(按此时间减开始时间结算)
	 */
	public function end($orderID,$endTime){
		$orderID = ( int ) $orderID;
		$endTime = ( float ) $endTime;
		// 获取订单
		$order = $this->getOneById ( $orderID );
		// 检查该订单是否已经被结算过,避免重复扣费
		if ($order ['isFinish'] == 1) {
			return array (
					'takeSec' => ( int ) $order ['takeSec'],
					'amount' => ( int ) $order ['amount']
			);
		}
		// 计算订单金额
		$takeSec = $endTime - $order ['beginTime'];

//		$this->load->model('Dev_mdl','dev');
//		$dev = $this->dev->getOneByID($order['devID']);
//		if ( ! empty($dev['schoolID']) && $dev['schoolID']==1 ) {
//			$price = 2;
//			$amount = $takeSec * 2;
//		}else{
//			$price = 1;
//			$amount = floor ( $takeSec / 3 ) * 4 + ($takeSec % 3) * 1;
//		}

 		$price = 1;
 		$amount = floor ( $takeSec / 3 ) * 4 + ($takeSec % 3) * 1;

		// 异常时不结算
		if ($amount < 0) {
			return FALSE;
		}
		// 向用户扣钱
		$res = $this->db->set ( 'balance', 'balance - ' . $amount, FALSE )
						->where ( 'id', $order ['userID'] )
						->update ( MY_Model::T_USER );
		if (! $res) {
			return FALSE;
		}
		// 更新order表
		$update = array (
				'endTime' => $endTime,
				'finishTime' => time (),
				'isFinish' => 1,
				'takeSec' => $takeSec,
				'amount' => $amount ,
				'price'=>$price
		);
		$where = array (
				'id' => $orderID
		);
		$this->update ( $where, $update );
		// 将该订单从消息队列删除
		$this->load->model ( 'Order_queue_mdl', 'orderQueue' );
		$this->orderQueue->removeOneByID ( $orderID );

// 		$this->load->model('Order_sync_queue_mdl','syncQueue');
// 		$this->syncQueue->enqueue(0,$order ['userID'],$orderID);

		return array (
				'takeSec' => ( int ) $takeSec,
				'amount' => ( int ) $amount
		);
	}

}

